package com.qingyun.form.items

import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.view.isVisible
import com.qingyun.form.R
import com.qingyun.form.base.FormType
import com.qingyun.form.base.FormViewHolder
import kotlin.math.tan

open class RadioGroupFormItem(
    label: String,
    name: String,
    value: String?,
    required: Boolean = false,
) : BaseFormItem(label, name, value) {
    override val formType: FormType
        get() = FormType.RadioGroup
    override val layoutId: Int
        get() = R.layout.form_item_radio

    override var hint: String? = null

    protected open val checkLabels = arrayOf("是", "否")

    open var checked: Boolean?
        get() = if (this.value == null) null else "true".equals(this.value)
        set(value) {
            this.value = value.toString()
        }
    protected open val checkLabel: String
        get() = when (checked) {
            true -> checkLabels[0]
            false -> checkLabels[1]
            else -> ""
        }

    init {
        this.required = required
    }

    override fun onBindViewHolder(holder: FormViewHolder) {
        holder.updateTitleLayout()
        holder.setVisibility(R.id.tvHint, !this.hint.isNullOrEmpty())
        holder.setText(R.id.tvHint, hint)
        holder.checkBox().text = checkLabels[0]
        holder.uncheckBox().text = checkLabels[1]
        val radioGroup = holder.radioGroup()
        radioGroup.isEnabled = this.enabled
        radioGroup.isVisible = !this.viewOnly
        when (this.checked) {
            null -> radioGroup.clearCheck()
            true -> radioGroup.check(R.id.rbChecked)
            false -> radioGroup.check(R.id.rbUnchecked)
        }
    }

    override fun onBindViewEvent(holder: FormViewHolder) {
        super.onBindViewEvent(holder)
        holder.radioGroup().setOnCheckedChangeListener(::onCheckedChanged)
    }

    override fun onUnBindViewEvent(holder: FormViewHolder) {
        super.onUnBindViewEvent(holder)
        holder.radioGroup().setOnCheckedChangeListener(null)
    }

    protected open fun onCheckedChanged(radioGroup: RadioGroup, checkId: Int) {
        val isChecked = when (checkId) {
            R.id.rbChecked -> true
            R.id.rbUnchecked -> false
            else -> null
        }
        val value = isChecked?.toString()
        onValueChanged(value)
    }

    override fun getTitleLayoutWidth(holder: FormViewHolder): Int {
        return holder.findTitleLayout().measuredWidth
    }

    protected open fun FormViewHolder.radioGroup(): RadioGroup {
        return this.getView(R.id.rgValue)
    }

    protected open fun FormViewHolder.checkBox(): RadioButton {
        return this.getView(R.id.rbChecked)
    }

    protected open fun FormViewHolder.uncheckBox(): RadioButton {
        return this.getView(R.id.rbUnchecked)
    }
}